import 'package:app_30/models/load_entity.dart';
import 'package:app_30/net/dio_utils.dart';
import 'package:app_30/net/http_api.dart';
import 'package:app_30/res/colors.dart';
import 'package:app_30/res/constant.dart';
import 'package:app_30/util/cache_utils.dart';
import 'package:app_30/util/change_notifier_manage.dart';
import 'package:app_30/util/dialog_utils.dart';
import 'package:app_30/util/other_utils.dart';
import 'package:app_30/util/toast_utils.dart';
import 'package:app_30/widgets/my_app_bar.dart';
import 'package:app_30/widgets/my_button.dart';
import 'package:app_30/widgets/my_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

import '../my_text_field.dart';

class TxPage extends StatefulWidget {
  const TxPage({Key? key}) : super(key: key);

  @override
  State<TxPage> createState() => _TxPageState();
}

class _TxPageState extends State<TxPage> with ChangeNotifierMixin<TxPage> {
  LoadEntity? loadEntity = getLoadData();
  String? money = getmoney();

  bool _clickable = false;
  final FocusNode _nodeTextzh = FocusNode();
  final FocusNode _nodeTextxm = FocusNode();
  final FocusNode _nodeTextxj = FocusNode();

  final TextEditingController _zhController = TextEditingController();
  final TextEditingController _xmController = TextEditingController();
  final TextEditingController _xjController = TextEditingController();

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _zhController: callbacks,
      _xmController: callbacks,
      _xjController: callbacks,
      _nodeTextzh: null,
      _nodeTextxm: null,
      _nodeTextxj: null,
    };
  }

  void _verify() {
    final String zh = _zhController.text;
    final String xm = _xmController.text;
    final String xj = _xjController.text;
    bool clickable = true;

    if (zh.isEmpty) {
      clickable = false;
    }
    if (xm.isEmpty) {
      clickable = false;
    }
    if (xj.isEmpty) {
      clickable = false;
    }
    if (double.parse(xj) < 0.1 || double.parse(xj) > double.parse(money!)) {
      clickable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(
          isBack: false,
          centerTitle: '提现',
        ),
        body: MyScrollView(
            keyboardConfig: Utils.getKeyboardActionsConfig(
                context, <FocusNode>[_nodeTextzh, _nodeTextxm, _nodeTextxj]),
            children: [
              Container(
                  decoration: BoxDecoration(
                    color: Colors.white10,
                  ),
                  child: Column(
                    children: [
                      Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(color: Colors.white),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                Text("支付宝账户:",
                                    style: TextStyle(
                                        fontSize: 15.5, color: Colors.grey)),
                                SizedBox(
                                  width: 8,
                                ),
                                Flexible(
                                  child: MyTextField(
                                    hintText: '请输入',
                                    controller: _zhController,
                                    focusNode: _nodeTextzh,
                                  ),
                                )
                              ],
                            ),
                            Row(
                              children: [
                                Text("收款人姓名:",
                                    style: TextStyle(
                                        fontSize: 15.5, color: Colors.grey)),
                                SizedBox(
                                  width: 8,
                                ),
                                Flexible(
                                  child: MyTextField(
                                    hintText: '请输入',
                                    controller: _xmController,
                                    focusNode: _nodeTextxm,
                                  ),
                                )
                              ],
                            ),
                            Row(
                              children: [
                                Text("提 现 金 额 :",
                                    style: TextStyle(
                                        fontSize: 15.5, color: Colors.grey)),
                                SizedBox(
                                  width: 8,
                                ),
                                Flexible(
                                  child: MyTextField(
                                    hintText: '请输入',
                                    keyboardType: TextInputType.number,
                                    controller: _xjController,
                                    focusNode: _nodeTextxj,
                                  ),
                                )
                              ],
                            ),
                            Padding(
                              padding: EdgeInsets.only(top: 10, bottom: 10),
                            ),
                            Row(
                              children: [
                                const Text("可提现金额:",
                                    style: TextStyle(
                                        fontSize: 15.5, color: Colors.grey)),
                                const SizedBox(
                                  width: 8,
                                ),
                                Expanded(
                                  child: Text(
                                    '${money}',
                                  ),
                                ),
                                SizedBox(
                                  height: 25,
                                  child: TextButton(
                                    child: const Text(
                                      "刷新",
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Colours.app_main),
                                    ),
                                    //添加一个点击事件
                                    onPressed: sx,
                                    //设置按钮是否自动获取焦点
                                    autofocus: true,
                                    style: ButtonStyle(
                                      padding: MaterialStateProperty.all(
                                          EdgeInsets.zero),
                                    ),
                                  ),
                                )
                              ],
                            ),
                            buildPadding(),
                            Text(
                              "注意:系统自动转账,目前暂时只支持支付宝提现，并且必须是已实名认证可以正常收款的支付宝账号，不可以是邮箱格式的支付宝账号。提现到账时间：最快十分钟之内，最晚次日24点之前。",
                              textAlign: TextAlign.left,
                              style:
                                  TextStyle(fontSize: 14, color: Colors.grey),
                            )
                          ],
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 40, left: 20, right: 20),
                        child: MyButton(
                          key: const Key('tixian'),
                          onPressed: _clickable ? _tixian : _checkText,
                          text: '确 认 提 现',
                        ),
                      )
                    ],
                  )),
            ]));
  }

  Padding buildPadding() {
    return Padding(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      child: SizedBox(
        width: double.infinity,
        height: 1,
        child: Container(
          color: Colors.grey,
        ),
      ),
    );
  }

  ButtonStyle buildButtonStyle() {
    return ButtonStyle(
      //定义文本的样式 这里设置的颜色是不起作用的
      textStyle: MaterialStateProperty.all(
          TextStyle(fontSize: 15, color: Colours.app_main)),
      //设置按钮上字体与图标的颜色
      //foregroundColor: MaterialStateProperty.all(Colors.deepPurple),
      //更优美的方式来设置
      foregroundColor: MaterialStateProperty.resolveWith(
        (states) {
          if (states.contains(MaterialState.focused) &&
              !states.contains(MaterialState.pressed)) {
            //获取焦点时的颜色
            return Colors.white;
          } else if (states.contains(MaterialState.pressed)) {
            //按下时的颜色
            return Colors.white70;
          }
          //默认状态使用灰色
          return Colors.white;
        },
      ),
      //背景颜色
      backgroundColor: MaterialStateProperty.resolveWith((states) {
        //设置按下时的背景颜色
        if (states.contains(MaterialState.pressed)) {
          return Colours.dark_app_main;
        }
        //默认不使用背景颜色
        return Colours.app_main;
      }),
      //设置水波纹颜色
      overlayColor: MaterialStateProperty.all(Colours.app_main),
      //设置阴影  不适用于这里的TextButton
      elevation: MaterialStateProperty.all(0),
      //设置按钮内边距
      padding: MaterialStateProperty.all(EdgeInsets.all(10)),
      //设置按钮的大小
      // minimumSize: MaterialStateProperty.all(Size(double.infinity,40)),
      //设置边框
      // side: MaterialStateProperty.all(BorderSide(color: Colors.grey, width: 1)),
      //外边框装饰 会覆盖 side 配置的样式
      // shape: MaterialStateProperty.all(StadiumBorder()),
    );
  }

  void _checkText() {
    sx();
    final String zh = _zhController.text;
    final String xm = _xmController.text;
    final String xj = _xjController.text;

    if (zh.isEmpty) {
      Toast.show('请输入支付宝账号');
      return;
    }
    if (xm.isEmpty) {
      Toast.show('请输入收款人名称，可只填名字的最后一个字');
      return;
    }
    if (xj.isEmpty) {
      Toast.show('请输入提现金额');
      return;
    }
    if (double.parse(xj) < 0.1 || double.parse(xj) > double.parse(money!)) {
      Toast.show('提现金额有误！不能大于您的帐户余额：${xj} 元，不能小于0.1 元');
      return;
    }
  }

  void sx() {
    setState(() {});
  }

  _tixian() async {
    final String zh = _zhController.text;
    final String xm = _xmController.text;
    final String xj = _xjController.text;

    Map<String, dynamic> map = Map();
    map['user'] = "${getUser()}";
    map['txje'] = "${xj}";
    map['txzh'] = "${zh}";
    map['txxm'] = "${xm}";
    map['txsantime'] = "";
    map['txtime'] = "";
    map['vip'] = "${loadEntity?.vip}";
    map['mac'] = getIdentifier();
    map['app'] = getPlatform();

    await DioUtils.instance.requestNetwork<String>(
      Method.post,
      HttpApi.tixian,
      params: map,
      onSuccess: (data) {
        showSingleDialog(context, '${Constant.msg}');

        setmoney("${double.parse(getmoney()!) - double.parse(Constant.jine)}");
        setState(() {
          money = getmoney();
          _zhController.text = '';
          _xmController.text = '';
          _xjController.text = '';
        });
      },
      onError: (_, __) {
        showSingleDialog(
          context,
          '${__}',
        );
      },
    );
  }
}
